﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

//创建节点
LTNode* BuyNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("BuyNode::malloc");
		exit(1);
	}
	newnode->val = x;
	newnode->next = newnode->prev = newnode;
	return newnode;
}
//初始化
LTNode* LTInit()
{
	LTNode* phead = BuyNode(-1);
	return phead;
}
//判断链表是否为空
bool LTEmpty(LTNode* phead)
{
	return (phead->next == phead);
}
//打印链表
void LTPrint(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->val);
		pcur = pcur->next;
	}
	printf("\n");
}
//尾插
void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* node = BuyNode(x);
	LTNode* pcur = phead->prev;
	node->next = phead;
	node->prev = pcur;

	pcur->next = node;
	phead->prev = node;
}
//尾删
void LTPopBack(LTNode* phead)
{
	assert(phead && phead->next != phead);
	LTNode* pcur = phead->prev;
	phead->prev = pcur->prev;
	pcur->prev->next = phead;
	free(pcur);
	pcur = NULL;
}
//头插
void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* node = BuyNode(x);
	LTNode* pcur = phead->next;
	node->next = pcur;
	node->prev = phead;

	pcur->prev = node;
	phead->next = node;
}
//头删
void LTPopFront(LTNode* phead)
{
	assert(phead && phead->next != phead);
	LTNode* pcur = phead->next;
	phead->next = pcur->next;
	pcur->next->prev = phead;
	free(pcur);
	pcur = NULL;
}
//链表查找
LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->val == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
//在pos位置之后插入数据
void LTInsert(LTNode* pos, LTDataType x)
{
	LTNode* pcur = pos->next;
	LTNode* node = BuyNode(x);
	node->next = pcur;
	node->prev = pos;
	pos->next = node;
	pcur->prev = node;
}
//删除pos节点
void LTErase(LTNode* pos)
{
	assert(pos);
	LTNode* pcur = pos->prev;
	pcur->next = pos->next;
	pos->next->prev = pcur;
	free(pos);
}
//销毁链表
void LTDestroy(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead) {
		LTNode* del = pcur;
		pcur = pcur->next;
		free(del);
	}
	free(phead);
}